package designpattern.proxy.jdk;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author zhangxin
 * @date 2020/10/29
 */
public class ProxyUtils {

    public static void generateClassFile(Class clazz, String proxyName) throws IOException {


        /**
         * 将根据类信息动态生成的二进制字节码保存到硬盘中，默认的是clazz目录下
         * params: clazz 需要生成动态代理类的类
         * proxyName: 为动态生成的代理类的名称
         */
        byte[] classFile = ProxyGenerator.generateProxyClass(proxyName, clazz.getInterfaces());

        String path = clazz.getResource(".").getPath();
        System.out.println(path);

        FileOutputStream out = null;

        try {
            out = new FileOutputStream(path + proxyName + ".class");
            out.write(classFile);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

}
